package com.learn.gateway.predicate;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author :wm
 * @description :自定义路由断言
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.MyRouteConfig> {

    private final static Logger log = LoggerFactory.getLogger(MyRoutePredicateFactory.class);

    public MyRoutePredicateFactory() {
        super(MyRouteConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRouteConfig config) {
        log.info("method:" + config.getMethod());
        return serverWebExchange -> serverWebExchange.getRequest().getMethod() == config.getMethod();
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(MyRouteConfig.FIELD_METHOD);
    }

    public static class MyRouteConfig {
        public final static String FIELD_METHOD = "method";

        public HttpMethod method;

        public HttpMethod getMethod() {
            return method;
        }

        public MyRouteConfig setMethod(HttpMethod method) {
            this.method = method;
            return this;
        }
    }
}
